package com.linx.open.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @ClassName: EncryptionUtils
 * @Description:
 * @Author: jxw
 * @Date: 2024-12-31 15
 */
public class EncryptionUtils {
    // 加密密钥，需和原代码中保持一致长度及内容（这里假设是固定的，实际应用要妥善管理）
    private static final String KEY = "YJWL202101010000";
    // 初始向量，需和原代码中保持一致长度及内容
    private static final String IV = "YJWL202101010000";

    /**
     * 加密方法，支持对字符串
     *
     * @param word 要加密的内容，可以是字符串或者对象
     * @return 加密后的Base64编码字符串
     * @throws Exception 如果加密过程出现问题抛出异常
     */
    public static String encryption(String word) throws Exception {
        byte[] keyBytes = KEY.getBytes(StandardCharsets.UTF_8);
        byte[] ivBytes = IV.getBytes(StandardCharsets.UTF_8);

        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encryptedBytes = cipher.doFinal(word.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 解密方法
     *
     * @param word 要解密的Base64编码后的字符串
     * @return 解密后的内容，以字符串形式返回（如果原先是对象加密的，返回对应的JSON解析后的对象对应的字符串）
     * @throws Exception 如果解密过程出现问题抛出异常
     */
    public static String decryption(String word) throws Exception {
        byte[] keyBytes = KEY.getBytes(StandardCharsets.UTF_8);
        byte[] ivBytes = IV.getBytes(StandardCharsets.UTF_8);

        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

        byte[] decodedBytes = Base64.getDecoder().decode(word);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);

        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        try {
            // 测试加密字符串
            String testString = "admin";
            String encryptedString = encryption(testString);
            System.out.println("加密后的字符串（Base64编码）: " + encryptedString);
            String encodedPassword = URLEncoder.encode(encryptedString, StandardCharsets.UTF_8);
            System.out.println("加密后的字符串（Base64编码）: " + encodedPassword);
            // 测试解密字符串
            String decryptedString = decryption(encryptedString);
            System.out.println("解密后的字符串: " + decryptedString);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
